const { body, param } = require('express-validator')
const validate = require('../middleware/validate')
const Article  = require('../model/article')

exports.createArticle = validate([
  body('article.title').notEmpty().withMessage('文章标题不能为空'),
  body('article.description').notEmpty().withMessage('文章摘要不能为空'),
  body('article.body').notEmpty().withMessage('文章内容不能为空')
])
exports.getArticle = validate([
  validate.isValidObjectId(['params'], 'articleId')
])
exports.updateArticle = [
  validate([
    validate.isValidObjectId(['params'], 'articleId')
  ]),
  async (req, res, next) => {
    const articleId = req.params.articleId
    const article = await Article.findById(articleId)
    if (!article) {
      return res.status(404).json({
        message: '文章不存在'
      })
    }
    req.article = article
    next()
  },
  async (req, res, next) => {
    // 如果当前登录人不是文章的作者，则没有权限更新文章
    if (req.user._id.toString() !== req.article.author.toString()) {
      return res.status(403).end()
    }
    next()
  }
]
exports.deleteArticle = exports.updateArticle
